/* Copyright (c) 2024 Qualcomm Technologies International, Ltd. */
/* %%version */

#include "gatt_ots_client_common_util.h"

/****************************************************************************/
void GattOtscTerminateReq(ServiceHandle svcHandle)
{
    GOTSC *otsClient = ServiceHandleGetInstanceData(svcHandle);

    GATT_OTS_CLIENT_INFO("GOTSC : GattOtscTerminateReq: svcHandle(0x%02x)\n", svcHandle);

    if (otsClient)
    {
        AppTask appTask               = otsClient->appTask;
        GattOtsClient *otsMainInst    = GattOtscGetMainInstance();
        GattOtscTerminateCfm *message = CsrPmemZalloc(sizeof(*message));

        message->svcHandle = otsClient->srvcElem->service_handle;

        /* Copy the device data to be returned */
        CsrMemCpy(&(message->deviceData), &(otsClient->deviceData), sizeof(GattOtscDeviceData));

        /* Un-register the GATT ID */
        CsrBtGattUnregisterReqSend(otsClient->srvcElem->gattId);

        /* Remove the service element from main instance's list */
        if (otsMainInst)
        {
            OTSC_REMOVE_SERVICE_HANDLE(otsMainInst->serviceHandleList, otsClient->srvcElem);
        }

        /* Free the service instance memory */
        if (ServiceHandleFreeInstanceData(svcHandle) == TRUE)
        {
            message->resultCode = GATT_OTSC_RESULT_CODE_SUCCESS;
        }
        else
        {
            message->resultCode = GATT_OTSC_RESULT_CODE_OPERATION_FAILED;
        }

        message->supplier = GATT_SUPPLIER_OTS_CLIENT;

        /* Send the CFM message now */
        GattOtscMessageSend(appTask, GATT_OTSC_TERMINATE_CFM, message);

        GATT_OTS_CLIENT_INFO("GOTSC: Terminated !\n");
    }
    else
    {
        /* No client found to send terminate cfm with failure */
        GATT_OTS_CLIENT_ERROR("GOTSC: No OTS client instance found !\n");
    }
}
